package com.example.petadopt.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.petadopt.R;
import com.example.petadopt.common.Result;
import com.example.petadopt.dao.PetDao;
import com.example.petadopt.entity.Pet;
import com.example.petadopt.ui.adapter.PetAdapter;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class AdminActivity extends AppCompatActivity {

    private TextView tvTitle;
    private TextView tvPetCount;
    private Button btnImportData;
    private Button btnAddPet;
    private Button btnLogout;
    private RecyclerView rvPetList;
    private PetAdapter petAdapter;
    private List<Pet> petList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);

        // 初始化视图
        initView();
        // 初始化监听器
        initListener();
        // 初始化数据
        initData();
    }

    private void initView() {
        tvTitle = findViewById(R.id.tv_title);
        tvPetCount = findViewById(R.id.tv_pet_count);
        btnImportData = findViewById(R.id.btn_import_data);
        btnAddPet = findViewById(R.id.btn_add_pet);
        btnLogout = findViewById(R.id.btn_logout);
        rvPetList = findViewById(R.id.rv_pet_list);

        // 设置RecyclerView
        rvPetList.setLayoutManager(new LinearLayoutManager(this));
        petAdapter = new PetAdapter();
        rvPetList.setAdapter(petAdapter);
    }

    private void initListener() {
        // 导入数据按钮
        btnImportData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                importPetData();
            }
        });

        // 添加宠物按钮
        btnAddPet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 跳转到添加宠物页面
                Intent intent = new Intent(AdminActivity.this, PetEditActivity.class);
                startActivity(intent);
            }
        });

        // 退出登录按钮
        btnLogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(AdminActivity.this);
                builder.setTitle("退出登录")
                        .setMessage("确定要退出登录吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(AdminActivity.this, LoginActivity.class);
                                startActivity(intent);
                                finish();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });

        // 设置宠物列表项点击事件
        petAdapter.setOnItemClickListener(new PetAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Pet pet) {
                Intent intent = new Intent(AdminActivity.this, PetDetailActivity.class);
                intent.putExtra("pet_id", pet.getId());
                intent.putExtra("is_admin", true); // 传递管理员标志
                startActivity(intent);
            }

            @Override
            public void onEditClick(Pet pet) {
                // 跳转到编辑宠物页面
                Intent intent = new Intent(AdminActivity.this, PetEditActivity.class);
                intent.putExtra("pet_id", pet.getId());
                startActivity(intent);
            }

            @Override
            public void onDeleteClick(Pet pet) {
                AlertDialog.Builder builder = new AlertDialog.Builder(AdminActivity.this);
                builder.setTitle("删除宠物")
                        .setMessage("确定要删除宠物 " + pet.getName() + " 吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                deletePet(pet);
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 每次回到页面时刷新数据
        initData();
    }

    private void initData() {
        // 获取宠物总数
        int petCount = PetDao.getPetCount();
        tvPetCount.setText("当前宠物总数: " + petCount);

        // 加载宠物列表
        loadPetList();
    }

    /**
     * 加载宠物列表
     */
    private void loadPetList() {
        Result<List<Pet>> result = PetDao.getAllPets();
        if (result.isSuccess() && result.getData() != null) {
            petList = result.getData();
            petAdapter.setPetList(petList);
        } else {
            Toast.makeText(this, "加载宠物列表失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 从assets导入宠物数据
     */
    private void importPetData() {
        try {
            // 打开JSON文件
            InputStream inputStream = getAssets().open("pet.json");
            // 从JSON加载宠物数据
            Result<List<Pet>> result = PetDao.loadPetsFromAssets(inputStream);

            if (result.isSuccess() && result.getData() != null) {
                List<Pet> petList = result.getData();
                // 将宠物数据导入到数据库
                Result<Void> importResult = PetDao.importPetsFromJson(petList);

                if (importResult.isSuccess()) {
                    Toast.makeText(this, "成功更新 " + petList.size() + " 条宠物数据", Toast.LENGTH_SHORT).show();
                    // 刷新宠物总数和列表
                    initData();
                } else {
                    Toast.makeText(this, importResult.getMessage(), Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "导入数据失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 删除宠物
     */
    private void deletePet(Pet pet) {
        Result<Void> result = PetDao.deletePet(pet.getId());
        if (result.isSuccess()) {
            Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show();
            // 刷新宠物总数和列表
            initData();
        } else {
            Toast.makeText(this, result.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

}